<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小西瓜 <751707632@qq.com.com>
// +----------------------------------------------------------------------
namespace app\fowl\model;

use app\admin\model\RouteModel;
use think\Model;
use think\Db;
use tree\Tree;

class ImsAddressModel extends Model
{
	/**
     * 地址编辑
     * @param array $data  地址信息
     * @return array
     */
    public function set($data){

    	if ( empty($data) ) {
    		return ['code'=>'0', 'msg'=>'缺少参数'];
    	}
    	$data_new = array();
    	if(isset($data['province_id'])) 	$data_new['province_id']	= $data['province_id'];
    	if(isset($data['city_id'])) 		$data_new['city_id']		= $data['city_id'];
    	if(isset($data['area_id'])) 		$data_new['area_id']		= $data['area_id'];
        if(isset($data['lat']))             $data_new['lat']            = $data['lat'];
        if(isset($data['lng']))             $data_new['lng']            = $data['lng'];
    	if(isset($data['address'])) 		$data_new['address']		= $data['address'];
    	if(isset($data['status'])) 			$data_new['address']		= $data['status'];

    	// 判断是否为默认地址
    	if (!empty($data['is_default']) &&  $data['is_default'] == 1) {
    		$this->where('is_default', 1)->update(['is_default'=>0]);
    		$data_new['is_default'] = 1;
    	} else {
    		$data_new['is_default'] = 0;
    	}

    	// 判断是增加还是修改
    	if(!empty($data['id']) && ($id = intval(trim($data['id'])))) {
    		$data_new['update_time'] = date('Y-m-d H:i:s', time());
    		$this->where('id', $id)->update($data_new);
    		return ['code'=>'1', 'msg'=>'修改成功'];
    	} else {
    		$data_new['create_time'] = date('Y-m-d H:i:s', time());
    		$id = $this->insert($data_new);
    		return ['code'=>'1', 'msg'=>'保存成功'];
    	}
    }

    /**
     * 地址列表
     * @return array
     */
    public function lists($where=[])
    {
    	$lists = $this->where($where)->select()->toArray();
    	foreach ( $lists as $key => $val ) {
    		if ( !empty($val['province_id']) ) {
    			$province = Db::name('ims_regions')->where('region_id',$val['province_id'])->value('region_name');
    		}
    		if ( !empty($val['city_id']) ) {
    			$city = Db::name('ims_regions')->where('region_id',$val['city_id'])->value('region_name');
    		}
    		if ( !empty($val['area_id']) ) {
    			$area = Db::name('ims_regions')->where('region_id',$val['area_id'])->value('region_name');
    		}
    		$lists[$key]['area'] = $province . ' ' . $city . ' ' . $area;
    	}

    	return $lists;
    }
}